package com.emm.thirdapp;

import android.app.Activity;
import android.content.Context;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

public class WebViewActivity extends Activity implements View.OnClickListener{

    private TextView title_action_close,title_action_back;
    private ImageButton title_action_left, title_action_reload;
    private WebView webView;
    private EditText etUrl;
    private TextView title_content;
    private LinearLayout ll_loading;
    private boolean urlIsShow = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        initView();
    }

    private void initView(){
        webView = (WebView) findViewById(R.id.webView);
        title_action_close = (TextView) findViewById(R.id.title_action_close);
        title_action_close.setOnClickListener(this);
        title_action_back = (TextView) findViewById(R.id.title_action_back);
        title_action_back.setOnClickListener(this);
        title_action_left = (ImageButton) findViewById(R.id.title_action_left);
        title_action_left.setOnClickListener(this);
        title_content =  (TextView) findViewById(R.id.title_content);
        title_content.setOnClickListener(this);
        title_action_reload = (ImageButton) findViewById(R.id.title_action_reload);
        title_action_reload.setOnClickListener(this);
        ll_loading = (LinearLayout) findViewById(R.id.ll_loading);
        ll_loading.setVisibility(urlIsShow ? View.VISIBLE : View.GONE);

        etUrl = (EditText)findViewById(R.id.et_url);
        findViewById(R.id.bt_load).setOnClickListener(this);

        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        // 设置可以支持缩放
        settings.setSupportZoom(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }
        // 设置可以使用localStorage
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
            settings.setDomStorageEnabled(true);
        }
        // 应用可以有数据库
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
            settings.setDatabaseEnabled(true);
            String databasePath = this.getDir("databases",
                    Context.MODE_PRIVATE).getPath();
            settings.setDatabasePath(databasePath);
        }
        // 应用可以有缓存
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
            settings.setAppCacheEnabled(true);
            settings.setLoadWithOverviewMode(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
            settings.setAllowFileAccess(true);
            settings.setBuiltInZoomControls(true);
            // 设置浏览器标识
            String ua = settings.getUserAgentString();
            settings.setUserAgentString("JQEMMSafeBrowser " + ua+".hxphone");
        }

        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        webView.setInitialScale(1); // 尝试设置为最小值，但效果可能因页面而异
    }

    @Override
    protected void onResume() {
        super.onResume();
        String strurl = "https://cms.wismed.com.cn/user/";
        reload(strurl);
    }

    private void reload(String strurl) {
        webView.loadUrl(strurl);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                Log.w("chevy","shouldOverrideUrlLoading url:"+url);
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                //handler.cancel(); 默认的处理方式，WebView变成空白页
                handler.proceed();//接受证书
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                Log.w("chevy","shouldInterceptRequest url:"+url);
//                if(url.equals("http://cas.telco.gx.cn:8003/cas/sso")){
////                    requestHttp(url);
//                    try {
//                        Log.w("chevy"," url:"+url);
//                        URL myurl = new URL("http://134.201.27.155:8003/cas/sso");
//                        URLConnection connection = myurl.openConnection();
//                        return new WebResourceResponse(connection.getContentType(), connection.getHeaderField("encoding"), connection.getInputStream());
//                    }catch (Exception e){
//                        Log.w("chevy"," e:"+e.getMessage());
//                    }
//
//                }
                return super.shouldInterceptRequest(view, url);
            }
            //WebView加载web资源
            //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        });
    }

    @Override
    public void onClick(View v) {
        int viewid = v.getId();
        if(viewid == R.id.title_action_close){
            finish();
        }else if(viewid == R.id.title_action_left || viewid == R.id.title_action_back){
            if (webView != null && webView.canGoBack()) {
                webView.goBack();// 返回前一个页面
            }
        } else if (viewid == R.id.bt_load) {
            reload(etUrl.getText().toString());
        } else if (viewid == R.id.title_content) {
            urlIsShow = !urlIsShow;
            ll_loading.setVisibility(urlIsShow ? View.VISIBLE : View.GONE);
        } else if (viewid == R.id.title_action_reload) {
            reload(etUrl.getText().toString());
        }
    }
}
